package org.linlinjava.litemall.app.interceptor;

import org.linlinjava.litemall.app.controller.BaseController;
import org.linlinjava.litemall.app.service.UserTokenManager;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AuthHandlerInterceptor implements HandlerInterceptor {

    public static final String Auth_TOKEN_KEY = "X-App-Token";

    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      /*  //获取控制器的名字
        System.out.println(((HandlerMethod) handler).getBean().getClass().getName());
        //获取方法名
        System.out.println(((HandlerMethod) handler).getMethod().getName());
*/

        String token = request.getHeader(Auth_TOKEN_KEY);
        if (token == null || token.isEmpty()) {
            throw new LoginException("未登陆");
        }
        Integer uid= UserTokenManager.getUserId(token);
        if(uid==null){
            throw new  LoginException("登录异常");
        }

        Object bean=((HandlerMethod) handler).getBean();
        if(bean instanceof BaseController) {
            BaseController controller= (BaseController) bean;
            controller.setUid(uid);
        }
        return true;
    }

}
